import { useState, useRef, useLayoutEffect } from "react";

const useResize = (ref) => {
  
  const observer = useRef(null)

  const [size, setSize] = useState({height: 20, width: 20});
  
  useLayoutEffect(() => {
    if (ref.current) {
      const {height, width} = ref.current.getBoundingClientRect();
  
      observer.current = new ResizeObserver(([{borderBoxSize:[{blockSize, inlineSize}]}]) => {
        setSize({height: blockSize, width: inlineSize});
      });
  
      observer.current.observe(ref.current, {box: 'border-box'});
  
      setSize({height, width})
    };
  
    return () => {
      observer.current && observer.current.disconnect();
    }
  }, [ref])

  return {size};
}

export default useResize;